import axios from 'axios'
import { reqReject, reqResolve, resReject, resResolve } from './interceptors'
import type { RequestConfig } from '~/types/axios'

interface ApiResponse<T = any> {
  code: number
  msg: string
  data: T
}

export function createAxios(options = {}) {
  const defaultOptions = {
    baseURL: import.meta.env.VITE_BASE_API,
    timeout: 12000,
  }
  const service = axios.create({
    ...defaultOptions,
    ...options,
  })
  service.interceptors.request.use(reqResolve, reqReject)
  service.interceptors.response.use(resResolve, resReject)
  return service
}
// 通用的请求函数 约束返回数据类型
// ApiResponse 主体固定后端返回格式
// T 泛型动态data数据类型，在api接口时定义
export default async function request<T>(config: RequestConfig) {
  return createAxios().request<ApiResponse<T>>(config).then(res => res.data)
}

